<?php

namespace system\model;

use hdphp\Model\Model;

class User extends Model
{
	//数据表
	protected $table = "user";

	//允许填充字段
	protected $allowFill = [];

	//禁止填充字段
	protected $denyFill = [];

	//完整表名
	protected $full = false;

	//自动验证
	protected $validate = [
		//['字段名','验证方法','提示信息',验证条件,验证时间]
	];

	//自动完成
	protected $auto = [
		//['字段名','处理方法','方法类型',验证条件,验证时机]
	];

	//自动过滤
	protected $filter = [
		//[表单字段名,过滤条件,处理时间]
	];

	//时间操作,需要表中存在created_at,updated_at字段
	protected $timestamps = false;

	//登录验证函数
	public function login(){
		$username = Q('post.username');
		$password = Crypt::encrypt(Q('post.password'));
		$code = strtoupper(Q('post.code'));
		$userData = Db::table('user')->where('username',$username)->first();
		if($username != $userData['username'] || $password != $userData['password']){
			$this->error = '用户名或密码错误';
			return false;
		}
		if($code != $_SESSION['code']){
			$this->error = '验证码错误';
			return false;
		}

		//登录成功
		$_SESSION['admin'] = ['uid' => $userData['uid'] , 'username' => $userData['username']];
		return true;
	}

	//修改密码
	public function edit(){
		$password = Q('post.password');						//原始密码
		$new_password = Q('post.new_password');				//新密码
		$confirm_password = Q('post.confirm_password');		//确认密码
		//根据存的session值来获取当前用户的数据
		$data = Db::table('user')->where('uid',$_SESSION['admin']['uid'])->first();

		//判断原始密码是否正确
		if($password != $data['password']){
//			p("原始密码都错啦");
			$this->error = "原始密码都错啦";
			return false;
		}

		//判断输入的新密码是否与旧密码相同，相同则提示错误
		if($new_password == $password){
			p("新旧密码相同你还修改什么");
			$this->error = "新旧密码相同你还修改什么";
			return false;
		}

		//判断两次密码是否输入一致
		if($confirm_password != $new_password){
			p("两次密码输入不一致");
			$this->error = "两次密码输入不一致";
			return false;
		}

		//进行修改
		$rows = Db::table('user')->where('uid',$_SESSION['admin']['uid'])->update(['password' => $new_password]);
		if(!$rows){
			//修改失败
			$this->error = '修改密码失败';
			return false;
		}

		return true;
	}
}